package pactice_handler

import (
	"fmt"
	"net/http"
	"peilian-api/app/global/bind"
	"peilian-api/app/global/common"
	"peilian-api/app/global/databases/elastic"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/log"
	"peilian-api/app/global/variable"
	"peilian-api/app/services"
	"peilian-api/app/services/view_service"
	"peilian-api/utils/format"
	"peilian-api/utils/tools"

	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
)

type WebReportDataResp struct {
	Url           string        `json:"url"`
	IsVip         bool          `json:"is_vip"`
	Theme         string        `json:"theme"`
	IsFirst       bool          `json:"is_first"`
	Criterias     []interface{} `json:"criterias"`
	ExceedPercent float64       `json:"exceed_percent"`
}

func WebReportData(c *gin.Context) {
	sessionId := c.Param("sessionId")
	var session tables.Session
	var wdr = WebReportDataResp{IsVip: false, Theme: tools.ThemeTopicDefault}
	// 1. 查询报告信息
	if err := variable.DB.MySQL.First(&session, sessionId).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	// 2. 查询用户身份
	if session.Type == tables.UserTypeNormal {
		wdr.IsVip = true
	} else {
		var user tables.User
		if err := variable.DB.MySQL.First(&user, session.UserID).Error; err != nil {
			format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
			return
		}
		if user.IsMember == tables.MemberStatusHas {
			wdr.IsVip = true
		}
	}
	if session.School == "北京大学" {
		wdr.Theme = tools.ThemeTopicBeida
	}
	wdr.Criterias = make([]interface{}, 0)
	// 查询所有的carterias
	sc := variable.DB.Redis.Get(common.RedisCriteriaKey)
	s, err := sc.Result()
	if err == nil && len(s) != 0 {
		var c []interface{}
		_ = json.Unmarshal([]byte(s), &c)
		wdr.Criterias = c
	}

	jsonUrl := variable.Config.UfsInfo.UfsUrl + variable.Config.UfsInfo.BucketPrefix + session.Url
	wdr.Url = jsonUrl
	var isFirst bool
	count, _ := new(tables.Session).FindSessionCountByUid(session.UserID)
	if count <= 1 {
		isFirst = true
	}
	wdr.IsFirst = isFirst

	// 报告总分超过人数占同岗位面试人数的百分比
	query := elastic.NewTermQuery("career_name", session.CareerName)
	startItem := &elastic.SplitItem{Key: fmt.Sprintf("%f以下", session.TotalScore), To: session.TotalScore}
	endItem := &elastic.SplitItem{Key: fmt.Sprintf("%f以上", session.TotalScore), From: session.TotalScore}
	aggs := elastic.NewRangeAggregation("score").RangeItem(startItem).RangeItem(endItem)
	res, err := elastic.NewEsClient().Size(0).Query(query).Aggregation("exceed_percent", aggs).Search()
	if err != nil {
		format.NewResponseJson(c).ErrObj(http.StatusBadRequest, err.Error())
		return
	}
	var esResp view_service.EsAggregationRes
	_ = json.Unmarshal(res, &esResp)
	var exceedPercent float64
	if esResp.Hits.Total.Value == 0 {
		exceedPercent = 0.2
		if session.TotalScore > 70 { // 大于70 才会显示超过了多少人
			var (
				lowCount int64
				allCount int64
			)
			variable.DB.MySQL.Model(&tables.Session{}).Where("total_score < ?", session.TotalScore).Count(&lowCount)
			variable.DB.MySQL.Model(&tables.Session{}).Count(&allCount)
			if allCount != 0 && lowCount != 0 {
				exceedPercent = float64(lowCount) / float64(allCount)
			} else {
				exceedPercent = float64(session.TotalScore-3) / 100
			}
		}
	} else {
		exceedPercent = float64(esResp.Aggregation.ExceedPercent.Buckets[0].DocCount) / float64(esResp.Hits.Total.Value)
		if exceedPercent >= 1 {
			exceedPercent = 0.95
		}
	}
	wdr.ExceedPercent = exceedPercent * 100
	// 更新报告已读
	go func() {
		updateResult := variable.DB.MySQL.Model(&tables.Session{}).Where("id=?", sessionId).Update("is_read", true)
		log.Logger.InfoF(c, fmt.Sprintf("update session read result:%+v", updateResult))
	}()

	format.NewResponseJson(c).SuccessObj(wdr)
}

func IsSharedCallback(c *gin.Context) {
	sessionId := c.Param("sessionId")
	variable.DB.MySQL.Model(&tables.Session{}).Where("id=?", sessionId).Update("is_shared", true)
	format.NewResponseJson(c).SuccessObj(struct{}{})
}

func IsSync(c *gin.Context) {
	var isSync services.SessionSync
	if err := bind.ShouldBinding(c, &isSync); err != nil {
		format.NewResponseJson(c).ErrObj(200, err.Error())
		return
	}
	sessionId := c.Param("sessionId")
	variable.DB.MySQL.Model(&tables.Session{}).Where("id=?", sessionId).Update("is_sync", isSync.IsSync)
	format.NewResponseJson(c).SuccessObj(struct{}{})
}
